package com.markby.fscm.cryptogram.domain.standard0009;

import lombok.Data;
import lombok.EqualsAndHashCode;
import org.bouncycastle.asn1.*;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;

/**
 * 0009规范 密钥对保护数据格式
 * SM2EnvelopedKey ::= SEQUENCE{
 * symAlgID				    AlgorithmIdentifier, 	--对称密码算法标识
 * symEncryptedKey			SM2Cipher,				--对称密钥密文
 * sm2PublicKey			    SM2PublicKey,			--SM2公钥
 * sm2EncryptedPrivateKey	BIT STRING 				--SM2私钥密文
 * }
 */
@EqualsAndHashCode(callSuper = true)
@Data
public class SM2EnvelopedKey extends ASN1Object {
    AlgorithmIdentifier symAlgID;
    SM2Cipher symEncryptedKey;
    SM2PublicKey sm2PublicKey;
    ASN1BitString sm2EncryptedPrivateKey;

    private SM2EnvelopedKey(ASN1Sequence sequence) {

        if (sequence.size() != 4) {
            throw new IllegalArgumentException("SM2EnvelopedKey sequence size must be 4");
        }
        symAlgID = AlgorithmIdentifier.getInstance(sequence.getObjectAt(0));
        symEncryptedKey = SM2Cipher.getInstance(sequence.getObjectAt(1));
        sm2PublicKey = SM2PublicKey.getInstance(sequence.getObjectAt(2));
        sm2EncryptedPrivateKey = ASN1BitString.getInstance(sequence.getObjectAt(3));

    }

    public static SM2EnvelopedKey getInstance(Object obj) {
        if (obj instanceof AlgorithmIdentifier) {
            return (SM2EnvelopedKey) obj;
        } else if (obj != null) {
            return new SM2EnvelopedKey(ASN1Sequence.getInstance(obj));
        }

        return null;
    }

    public SM2EnvelopedKey(AlgorithmIdentifier symAlgID, SM2Cipher symEncryptedKey, SM2PublicKey sm2PublicKey, ASN1BitString sm2EncryptedPrivateKey) {
        this.symAlgID = symAlgID;
        this.symEncryptedKey = symEncryptedKey;
        this.sm2PublicKey = sm2PublicKey;
        this.sm2EncryptedPrivateKey = sm2EncryptedPrivateKey;
    }

    public SM2EnvelopedKey(SM2Cipher symEncryptedKey, SM2PublicKey sm2PublicKey, ASN1BitString sm2EncryptedPrivateKey) {
//        String SGD_SM4_ECB = "00000401";
//        BigInteger symInteger = new BigInteger(SGD_SM4_ECB, 16);
//        ASN1Integer symOid = new ASN1Integer(symInteger);
        String SM4_OID = "1.2.156.10197.1.104";
        AlgorithmIdentifier symAlgID = new AlgorithmIdentifier(new ASN1ObjectIdentifier(SM4_OID));
        this.symAlgID = symAlgID;
        this.symEncryptedKey = symEncryptedKey;
        this.sm2PublicKey = sm2PublicKey;
        this.sm2EncryptedPrivateKey = sm2EncryptedPrivateKey;
    }

    @Override
    public ASN1Primitive toASN1Primitive() {
        ASN1EncodableVector vector = new ASN1EncodableVector(4);
        vector.add(symAlgID);
        vector.add(symEncryptedKey);
        vector.add(sm2PublicKey);
        vector.add(sm2EncryptedPrivateKey);
        return new DERSequence(vector);
    }
}
